import React, { useState } from 'react';
import ProTable from '@ant-design/pro-table';
import { PlusOutlined } from '@ant-design/icons';
import type { ProColumns, ActionType } from '@ant-design/pro-table';
import { ModelDesign } from 'bsin-workflow-ui';
import {
  Card,
  Col,
  Row,
  Button,
  Popover,
  Modal,
  Form,
  Input,
  Popconfirm,
  message,
  Select,
  Tree,
} from 'antd';
// 搜索 表头
import { columnsData, treeData, ModelType } from './data';
import type { modelInfoType } from './data.d';
// 模拟的数据
import tableData from '../../mock/tableData';
import {
  getPageListModel,
  saveModel,
  deployModel,
  getModelById,
  deleteModel,
  getModelTypeTree,
} from '../../services/modelDefinition';
import SearchTree from '../../components/SearchTree';

const { TextArea } = Input;
const { Search } = Input;

const ModelDefinition = () => {
  // 新增表单
  const [addForm] = Form.useForm();
  // table 绑定
  const tableRef = React.useRef<ActionType>();
  // 控制新增模态框
  const [isAddInfoModalVisible, setIsAddInfoModalVisible] = useState(false);
  // 设计模态框
  const [isDesignerModalVisible, setIsDesignerModalVisible] = useState(false);
  // 在编辑的模板
  const [editModel, setEditModel] = useState<modelInfoType>();
  // 新增模态框确认按钮loading状态
  const [addOkLoading, setAddOkLoading] = useState<boolean>(false);
  // 模型类型树数据
  const [treeData, setTreeData] = useState([]);
  // 模型类型 id
  const [modelTypeId, setModelTypeId] = useState('');

  // 表头数据
  const columns: ProColumns<modelInfoType>[] = columnsData;

  React.useEffect(() => {
    getModelsTypeTree();
  }, []);

  // 获取模板类型tree
  const getModelsTypeTree = async () => {
    let res = await getModelTypeTree({});
    if (res.code !== '000000') {
      message.error('获取模板类型树失败');
      return;
    }
    let orgList = setTree(res.data);
    setTreeData(orgList);
  };

  // 打造机构树
  const setTree = (arr: any) => {
    let tree = arr?.map((item: any) => {
      let obj = {
        title: item.typeName,
        key: item.id,
        children: [],
      };
      if (item.children.length !== 0) {
        obj.children = setTree(item.children);
      }
      return obj;
    });
    return tree;
  };

  // 设计按钮
  const designer = async (record: modelInfoType) => {
    // 获取对应模板的xml信息
    let res = await getModelById({ id: record.id });
    if (res.code !== '000000') {
      message.error('获取流程图信息失败');
      return;
    }
    record.bpmnModelXml = res.data;
    setEditModel(record);
    setIsDesignerModalVisible(true);
  };

  // 改变模型类型
  const changeModelType = (id: string) => {
    setModelTypeId(id);
  };

  // 删除提醒 确认按钮
  const confirmDel = async (id: string) => {
    let res = await deleteModel({ id });
    tableRef.current?.reload();
    if (res.code == '000000') {
      message.success('删除成功');
    } else {
      message.error('删除失败');
    }
  };

  // 气泡框
  const content = (
    <div className="popover-text">
      <p>查看流程图</p>
      <p>导出XML文件</p>
      <p>查看基础信息</p>
      <p>编辑基础信息</p>
    </div>
  );

  // 操作行数据 自定义操作行
  const actionRender: any = (
    text: any,
    record: modelInfoType,
    index: number,
  ) => (
    <ul className="ant-list-item-action" style={{ margin: 0, width: 230 }}>
      <li>
        <a onClick={() => designer(record)}>设计</a>
        <em className="ant-list-item-action-split"></em>
      </li>
      <li>
        <a
          onClick={async () => {
            let res = await deployModel({ id: record.id });
            if (res.code == '000000') {
              message.success('部署成功');
            } else {
              message.error('部署失败');
            }
          }}
        >
          部署
        </a>
        <em className="ant-list-item-action-split"></em>
      </li>
      <li>
        <Popconfirm
          className="delPopconfirm"
          title="是否确认删除？"
          okText="是"
          cancelText="否"
          onConfirm={() => {
            confirmDel(record.id);
          }}
        >
          <a onClick={() => {}}>删除</a>
        </Popconfirm>
        <em className="ant-list-item-action-split"></em>
      </li>
      <li>
        <Popover content={content} placement="bottomLeft">
          <a>更多</a>
        </Popover>
      </li>
    </ul>
  );

  // 自定义数据的表格头部数据
  columns.forEach((item: any) => {
    item.dataIndex === 'action' ? (item.render = actionRender) : undefined;
  });

  // 打开新增模态框
  const addInfo = () => {
    setIsAddInfoModalVisible(true);
  };

  // 新增模态框确定
  const addModeOk = async () => {
    setAddOkLoading(true);
    let addFormData = addForm.getFieldsValue();
    if (!modelTypeId) {
      message.error('请选择模型类型');
      setAddOkLoading(false);
      return;
    }
    let res = await saveModel({ ...addFormData, modelTypeId, modelType: 0 });
    if (res.code == '000000') {
      message.success('添加成功');
      tableRef.current?.reload();
      addForm.resetFields();
    } else {
      message.error('添加失败');
    }
    setAddOkLoading(false);
    setIsAddInfoModalVisible(false);
  };

  // 新增模态框取消
  const addModeCancel = () => {
    addForm.resetFields();
    setIsAddInfoModalVisible(false);
  };

  return (
    <div>
      <Row gutter={18}>
        {/* 左侧 */}
        <Col span={6}>
          <Card>
            <SearchTree
              // 渲染数据
              checkedId={modelTypeId}
              treeData={treeData}
              changeKey={changeModelType}
            />
          </Card>
        </Col>
        {/* 右侧 */}
        <Col span={18}>
          <Card>
            {/* Pro表格 */}
            <ProTable<modelInfoType>
              actionRef={tableRef}
              headerTitle="模型管理"
              bordered
              scroll={{ x: 1000 }}
              // 表格格式
              columns={columns}
              params={{ modelTypeId }}
              // 请求获取的数据
              request={async (params) => {
                let res = await getPageListModel({
                  ...params,
                  pageNum: params.current,
                });
                if (res.code !== '000000') {
                  message.error('获取模型管理表格信息失败');
                }
                const result = {
                  data: res.data,
                  total: res.pagination?.totalSize,
                };
                return result;
              }}
              // dataSource={tableData}
              rowKey="id"
              // 本地存储表格列的显示数据
              columnsState={{
                persistenceKey: 'model-definition',
                persistenceType: 'localStorage',
              }}
              // 搜索框配置
              search={{
                labelWidth: 'auto',
              }}
              // 搜索表单的配置
              form={{
                ignoreRules: false,
              }}
              pagination={{
                pageSize: 5,
              }}
              dateFormatter="string"
              //设置工具栏按钮及事件
              toolBarRender={() => [
                // 新增模板按钮
                <Button
                  key="button"
                  icon={<PlusOutlined />}
                  type="primary"
                  onClick={addInfo}
                >
                  新增
                </Button>,
              ]}
            />
          </Card>
        </Col>
      </Row>
      {/* 增加模态框 */}
      <Modal
        centered
        width={700}
        title="新建"
        open={isAddInfoModalVisible}
        onOk={addModeOk}
        onCancel={addModeCancel}
        confirmLoading={addOkLoading}
      >
        <Form
          form={addForm}
          name="basic"
          labelCol={{ span: 5 }}
          wrapperCol={{ span: 16 }}
          autoComplete="off"
        >
          {/* <Form.Item
            label="分类"
            name="modelType"
            rules={[{ required: true, message: '请选择模型类型' }]}
          >
            <Select options={ModelType} />
          </Form.Item> */}
          <Form.Item
            label="名称"
            name="name"
            rules={[{ required: true, message: '请输入模型名称' }]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            label="标识编码"
            name="key"
            rules={[{ required: true, message: '请输入模型唯一的编码' }]}
          >
            <Input />
          </Form.Item>
          <Form.Item label="描述" name="description">
            <TextArea rows={4} />
          </Form.Item>
        </Form>
      </Modal>
      {/* 设计模态框 */}
      {isDesignerModalVisible ? (
        <div className="designer-modal">
          <span
            onClick={() => {
              setIsDesignerModalVisible(false);
            }}
            className="close-designer"
          >
            x
          </span>
          <ModelDesign editModel={editModel}></ModelDesign>
        </div>
      ) : null}
    </div>
  );
};

export default ModelDefinition;
